from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from myadmin import models
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse
# Create your views here.
def index(request):
    ob = models.Cates.objects.filter(pid=0)
    for i in ob:
        i.sub= models.Cates.objects.filter(pid=i.id)


    dd=models.Cates.objects.filter(pid=0).exclude(name='手机')
    for i in dd:
        i.dd=models.Cates.objects.filter(pid=i.id)
        # print(i.dd)
    # i.dd=models.Goods.objects.all()[:5]

    return render(request,'myhome/index.html',{'info':ob,'dd':dd})

def goodslist(request):
    cid = request.GET.get('id')
    # print(cid)
    ctype = models.Cates.objects.get(id=cid)
    types = models.Cates.objects.filter(id=ctype.pid)
    data=ctype.goods_set.all().filter(gnum__gt=0)
    if request.GET.get('new') == 'status':
        data = ctype.goods_set.all().filter(gnum__gt=0).filter(status=0).order_by('-addtime')
    elif request.GET.get('new') == 'price':
        data = ctype.goods_set.all().filter(gnum__gt=0).order_by('-price')
    # return render(request,'myhome/list.html')
    # return HttpResponse('<script>location.href("'+reverse('myhome_list')+'")</script>')
    # print(data,ctype,types)
    return render(request,'myhome/list.html',{'data':data,'ctype':ctype,'types':types})

def goodsinfo(request):
    gid=request.GET.get('id')
    data=models.Goods.objects.filter(id=gid)
    return render(request,'myhome/info.html',{'data':data[0]})

def login(request):
    if request.method == 'GET':
        return render(request,'myhome/login.html')
    elif request.method == 'POST':
        data = request.POST.dict()
        # print(data)
        try:
            ob = models.Users.objects.get(phone=data['phone'])
            obpass=check_password(data['password'],ob.password)
            if ob and obpass:
                request.session['vipuser']={'username':ob.username,'phone':ob.phone}
                return HttpResponse('<script>alert("登陆成功");location.href="'+reverse('myhome_index')+'"</script> ')
            else:
                return HttpResponse('<script>alert("用户名或者密码错误");history.back(-1);</script>')
        except:
            return HttpResponse('<script>alert("用户名不存在");history.back(-1);</script>')
def loginout(request):
    del request.session['vipuser']
    return HttpResponse('<script>alert("退出成功");location.href="/"</script>')

def register(request):
    if request.method=='GET':
        # request.session['msgcode'] = {'code':code,'phone':'11111111111'}
        return render(request,'myhome/register.html')
    elif request.method=='POST':
        data=request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        if request.session['msgcode']['code']==data['code'] and request.session['msgcode']['phone']==data['phone']:
            data['password']=make_password(data['password'],None,'pbkdf2_sha256')
            info={'username':'user'+data['phone'],'phone':data['phone'],'password':data['password'],'pic_url':'/static/myadmin/pics/user.png'}
            ob=models.Users(**info)
            ob.save()
            return HttpResponse('<script>alert("注册成功");location.href="'+reverse('myhome_login')+'"</script>')
        else:
            return HttpResponse('<script>alert("验证错误");location.href="'+reverse('myhome_register')+'"</script>')

            

def checkregister(request):
    # 获取提交的用户名
    p = request.GET.get('phone')
    # 根据yonghu数据查询数据
    ob = models.Users.objects.filter(phone=p)
    if ob:
        # 如果查询导数据用户名已经被注册
        return JsonResponse({"error":0,'msg':'用户名已注册'})
    else:
        return JsonResponse({"error":1,'msg':'用户名可用'})


def goodscart(request):
    # cha xun 
    userphone = request.session['vipuser']['phone']
    user = models.Users.objects.get(phone=userphone)
    # print(user.id)
    goods = user.cart_set.all()
    return render(request,'myhome/cart.html',{'data':goods})
# 购物车添加
def goodscartadd(request):
    data = request.GET.dict()
    user = models.Users.objects.get(phone=data['phone'])
    goods = models.Goods.objects.get(id=data['gid'])
    ob = models.Cart.objects.filter(uid=user).filter(gid=goods)

    if ob:
        for i in ob:
            i.gnum=i.gnum+int(data['num'])
        ob[0].save()
    else:
        c = models.Cart()
        c.uid = user 
        c.gid = goods
        c.gnum = int(data['num'])
        c.save()
    return JsonResponse({'error':1})


def goodscartre(request):
    # 接受数据
    data = request.GET.dict()
    user = models.Users.objects.get(phone=request.session['vipuser']['phone'])
    g=models.Goods.objects.get(id=data['gid'])
    # 修改
    goods = models.Cart.objects.filter(uid=user).filter(gid=g)
    # print(goods)
    # 查询集 更新数据 需遍历 才能操作更新
    pricesum=0
    for i in goods:
        i.gnum=data['num']
        i.save()
        cid = i.id
        pricesum=float(i.gnum)*float(i.gid.price)

    return JsonResponse({'error':1,'pricesum':pricesum,'cid':cid})

def goodscartdell(request):
    cid=request.GET.get('cid')
    ob=models.Cart.objects.get(id=cid)
    ob.delete()

    return JsonResponse({'error':1})

# 订单
def order(request):
    res=request.GET.get('cid')
    clist = res.split(',')
    data = models.Cart.objects.filter(id__in=clist)
    user=models.Users.objects.get(phone=request.session['vipuser']['phone'])
    address=models.Address.objects.filter(uid=user.id)
    # 讲数据序列化[{},{}]
    adds=list(address.values())
    for i in adds:
        xq = models.Citys.objects.get(id=i['zhen_id'])
        shi = models.Citys.objects.get(id=xq.upid)
        sheng = models.Citys.objects.get(id=shi.upid)
        i['shi']=shi.name
        i['sheng'] = sheng.name
        i['zhen_id']=xq.name

    citys=models.Citys.objects.filter(level=1)
    return render(request,'myhome/order.html',{'data':data,'citys':citys,'address':adds})
#  获取地址  城际联动
def goodscitys(request):
    uid=request.GET.get('upid')
    data = models.Citys.objects.filter(upid=uid).values()
    return JsonResponse(list(data),safe=False)

# 保存收货地址
def saveadd(request):
    data=request.GET.dict()
    try:
        ob=models.Address()
        ob.uid=models.Users.objects.get(phone=request.session['vipuser']['phone'])
        ob.shr=data['name']
        ob.phone=data['phone']
        ob.zhen =models.Citys.objects.get(id=data['citys'])
        ob.info=data['info']
        ob.save()
        return JsonResponse({'error':1})
    except:
        return JsonResponse({'error':0})

def deladd(request):
    cid=request.GET.get('cid')
    data=models.Address.objects.get(id=cid)
    data.delete()

    return JsonResponse({'error':1})

def person(request):
    up = request.session['vipuser']['phone']
    user = models.Users.objects.get(phone=up)
    data = request.POST.dict()
    # print(data)
    
    if request.method=='GET':

        return render(request,'myhome/person.html',{'info':user})
    if request.method=='POST':
        user.name=request.POST.get('username')
        user.sex=request.POST.get('sex')
        user.email=request.POST.get('email')
    user.save()
    return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myhome_person')+'"</script>')



def orderinfo(request):
    if request.method=='GET':
        data = models.Order.objects.all()
        print(data)
        for i in data:
            print(i)
            i.data=i.orderinfo_set.all()
            print(i.data)
        return render(request,'myhome/orderinfo.html',{'data':data})
    if request.method=='POST':
        orderdata = request.POST.dict()
        orderdata.pop('csrfmiddlewaretoken')

        # 获取用户对象
        orderdata['uid']=models.Users.objects.get(phone=request.session['vipuser']['phone'])
        # 地址
        address = models.Address.objects.get(id=orderdata['addrid'])
        xq = models.Citys.objects.get(id=address.zhen_id)
        shi = models.Citys.objects.get(id=xq.upid)
        sheng = models.Citys.objects.get(id=shi.upid)
        # print(xq.name,shi.name,sheng.name)
        orderdata['addr']=sheng.name+shi.name+xq.name+address.info

        # 总价格
        res = orderdata['cid'].split(',')
        # 查询数据
        goos = models.Cart.objects.filter(id__in=res)
        pricesume=0
        for i in goos:
            pricesume += i.gnum*i.gid.price

        orderdata['price']=pricesume

        # 删除不需要数据
        orderdata.pop('cid')
        orderdata.pop('addrid')
        print(orderdata,res)
        # 添加数据
        order = models.Order(**orderdata)
        order.save()

        # 添加订单详情 一个订单有多个商品  一个商品就是一个订单详情
        for i in res:
            orderinfo = models.Orderinfo()
            orderinfo.ordid= order
            goods = models.Cart.objects.get(id=i)
            orderinfo.gid=goods.gid.id
            orderinfo.title=goods.gid.title
            orderinfo.num=goods.gnum
            orderinfo.pic_url=goods.gid.pic_url
            orderinfo.save()

            # 删除购物车里的商品
            goods.delete()


        return render(request,'myhome/person.html')



# 短信验证
def sendmsg(request):
    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
    import urllib
    import urllib.request
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C70849323" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "eda6a3484bc918b442a5b9c4fabb3a83"
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000,99999))
    # 把验证码存入session
    print(code)
    request.session['msgcode'] = {'code':code,'phone':mobile}
    text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    # req = urllib.request.urlopen(
    #     url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
    #     data= urllib.parse.urlencode(data).encode('utf-8')
    # )
    # content =req.read()
    # res = json.loads(content.decode('utf-8'))
    # print(res)
    return HttpResponse('res')
